# -*- coding:utf-8 -*-
# !usr/bin/env python
import signal
import time

import pexpect
import sys
import os

sys.path.append(os.path.join(sys.path[0], '../..'))
from csi_config import read_setting

wlan = read_setting('wlan')
PASSWD = read_setting('password')
interval = 0.1
childs = []


def error(err=0):
    if err == 0:
        print("Error - EOF! -- zz")
    elif err == 1:
        print("Error - TIMEOUT! -- zz")
    sys.exit(-1)


def getaddr(s):
    st = s.find('from')
    en = s.rfind('\r')
    st2 = s.find('of')
    en2 = s.rfind('from')
    return s[st + 5:en], s[st2 + 3:en2 - 1]


if __name__ == '__main__':

    if len(sys.argv) == 1:
        ssid = input('Input ssid name:')
    elif len(sys.argv) == 2:
        if '-c' in sys.argv:
            ssid = read_setting('ssid')
        else:
            ssid = sys.argv[1]
    else:
        print('Usage:init [<ssid>]')
        raise RuntimeError
    child = pexpect.spawn('sudo iw dev %s connect %s' % (wlan, ssid))
    try:
        index = child.expect('password')
        if index == 0:
            child.sendline(PASSWD)
    except pexpect.EOF:
        error()
    while child.isalive():
        pass
    print("Connect %s [%s] OK! -- zz" % (wlan, ssid))
    child = pexpect.spawn('sudo dhclient -r')
    try:
        index = child.expect('password')
        if index == 0:
            child.sendline(PASSWD)
    except pexpect.EOF:
        error()
    while child.isalive():
        pass
    time.sleep(1)
    child = pexpect.spawn('sudo dhclient -d')
    try:
        index = child.expect('password')
        if index == 0:
            child.sendline(PASSWD)
            index1 = child.expect(['DHCPACK.*\n'])
            if index1 == 0:
                addr, addr2 = getaddr(child.after.decode('utf8'))
                print("%s->%s" % (addr, addr2))


    except pexpect.EOF:
        error()
        child.kill(signal.SIGKILL)
    except pexpect.TIMEOUT:
        child.kill(signal.SIGKILL)
        error(1)
